package com.banmao.mall.service.admin.impl;

import com.alibaba.druid.util.StringUtils;
import com.banmao.mall.mapper.*;
import com.banmao.mall.model.bo.admin.market.*;
import com.banmao.mall.model.pojo.*;
import com.banmao.mall.model.vo.admin.market.*;
import com.banmao.mall.service.admin.MarketService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Transactional
@Service
public class MarketServiceImpl implements MarketService {

    // 注入Mapper组件
    @Autowired
    RegionMapper regionMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    StorageMapper storageMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    IssueMapper issueMapper;
    @Autowired
    KeywordMapper keywordMapper;

    // 图片路径前缀
    // 在输出图片或者将图片地址存入数据库中时使用
    @Value("${myimage.baseURL}")
    private String imageBaseURL;
    @Value("${myimage.fileSavePath}")
    private String fileSavePath;

    //private static Integer picID = 0;

    @Override
    public List<ProvinceVO> regionList() {

        // 根据type=1获取省的基本信息
        List<ProvinceVO> provinceVOList = regionMapper.selectAllProvince();
        // 遍历省集合
        for (ProvinceVO provinceVO : provinceVOList) {
            // 根据省id获取市的基本信息
            List<CityVO> cityVOList = regionMapper.selectAllCityByPID(provinceVO.getId());

            // 遍历市集合
            for (CityVO cityVO : cityVOList) {
                // 根据市id获取区的基本信息
                List<AreaVO> areaVOList = regionMapper.selectAllAreaByPID(cityVO.getId());
                // 将area集合放入city集合中
                cityVO.setChildren(areaVOList);
            }

            // 将city集合放入province集合中
            provinceVO.setChildren(cityVOList);
        }


        return provinceVOList;
    }

    @Override
    public BrandListVO brandList(BrandListBO brandListBO) {

        // 分页插件
        PageHelper.startPage(brandListBO.getPage(), brandListBO.getLimit());

        List<BrandVO> brandVOS = brandMapper.selectBrandByCondition(brandListBO);
        for (BrandVO brandVO : brandVOS) {
            if(!brandVO.getPicUrl().startsWith("http")) {
                brandVO.setPicUrl(imageBaseURL + brandVO.getPicUrl());
            }
        }

        PageInfo<BrandVO> brandVOPageInfo = new PageInfo<>(brandVOS);
        long totalCount = brandVOPageInfo.getTotal();

        BrandListVO brandListVO = new BrandListVO();
        brandListVO.setTotal(totalCount);
        brandListVO.setItems(brandVOS);

        return brandListVO;
    }

    @Override
    public FileUploadVO fileUpload(MultipartFile multipartFile, HttpServletRequest request) {
        // 获取文件名
        String filename = multipartFile.getOriginalFilename();
        // 当文件名过长时，修剪保留前23个字符
        if(filename.length() >= 23) {
            filename = filename.substring(filename.length() - 23);
        }
        // 为了解决文件重名问题，在文件名前加上随机生成的UUID
        UUID uuid = UUID.randomUUID();
        filename = uuid + "-" + filename;

        // 为了将文件的保存目录下文件数量分布均匀
        // 使用散列得到文件名的HASH值
        int hashCode = filename.hashCode();
        // 得到hash值的16进制
        String hexString = Integer.toHexString(hashCode);
        // 根据16进制的8个值创建目录，将文件保存至第八个目录里
        char[] chars = hexString.toCharArray();
        // 基础目录
        StringBuilder basePath = new StringBuilder();
        for (char aChar : chars) {
            basePath.append("/").append(aChar);
        }
        // 获取文件的相对路径
        String relativePath = basePath.toString() + "/" + filename;
        // 获取文件的绝对路径
        String absolutePath = fileSavePath + relativePath;
        // 创建文件对象
        File file = new File(absolutePath);
        // 如果目录不存在，就创建
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        FileUploadVO fileUploadVO = new FileUploadVO();
        //fileUploadVO.setId(++picID);
        fileUploadVO.setName(multipartFile.getOriginalFilename());
        fileUploadVO.setKey(filename);
        fileUploadVO.setType(multipartFile.getContentType());
        fileUploadVO.setSize(multipartFile.getSize());
        fileUploadVO.setUrl(imageBaseURL + relativePath.replace("static/images", ""));
        fileUploadVO.setAddTime(new Date());
        fileUploadVO.setUpdateTime(new Date());
        //存储到storage表
        Storage storage = new Storage();
        //storage.setId(fileUploadVO.getId());
        storage.setKey(fileUploadVO.getKey());
        storage.setName(fileUploadVO.getName());
        storage.setType(fileUploadVO.getType());
        storage.setSize(Integer.parseInt(String.valueOf(fileUploadVO.getSize())));
        storage.setUrl(fileUploadVO.getUrl());
        storage.setAddTime(fileUploadVO.getAddTime());
        storage.setUpdateTime(fileUploadVO.getUpdateTime());
        storage.setDeleted(false);
        storageMapper.insert(storage);

        // 将Storage的回传主键放入fileUploadVo对象中
        fileUploadVO.setId(storage.getId());

        return fileUploadVO;
    }

    @Override
    public BrandVO brandUpdate(BrandBO brandBO) {

        // 去除本地图片的前缀，存入数据库
        if(brandBO.getPicUrl() != null) {
            brandBO.setPicUrl(brandBO.getPicUrl().replace(imageBaseURL, ""));
        }

        int result = brandMapper.updateByPrimaryKeySelective(brandBO);
        if(result == 0) {
            return null;
        }

        BrandVO brandVO = brandMapper.selectByPrimaryKey(brandBO.getId());
        if(!brandVO.getPicUrl().startsWith("http")) {
            // 回显时加上图片路径前缀
            brandVO.setPicUrl(imageBaseURL + brandVO.getPicUrl());
        }

        return brandVO;
    }

    @Override
    public BrandVO brandCreate(BrandBO brandBO) {

        if(brandBO.getPicUrl() != null) {
            brandBO.setPicUrl(brandBO.getPicUrl().replace(imageBaseURL, ""));
        }

        int result = brandMapper.insertSelective(brandBO);
        if(result == 0) {
            return null;
        }

        BrandVO brandVO = brandMapper.selectByPrimaryKey(brandBO.getId());
        if(!brandVO.getPicUrl().startsWith("http")) {
            brandVO.setPicUrl(imageBaseURL + brandVO.getPicUrl());
        }

        return brandVO;
    }

    @Override
    public int brandDelete(BrandBO brandBO) {

        // 逻辑删除品牌商
        int result = brandMapper.updateDeletedByID(brandBO.getId());

        return result;
    }

    @Override
    public List<CategoryL1VO> categoryL1() {

        // 获取一级类目的基本信息（不知道有啥用的请求）
        List<CategoryL1VO> categoryL1VOS = categoryMapper.selectL1BaseInfo();

        return categoryL1VOS;
    }

    @Override
    public List<CategoryVO> selectAllCategory() {

        // 获取一级类目集合
        List<CategoryVO> categoryVOList = categoryMapper.selectL1();

        // 遍历一级类目
        for (CategoryVO categoryVO : categoryVOList) {
            if(!categoryVO.getIconUrl().startsWith("http")) {
                categoryVO.setIconUrl(imageBaseURL + categoryVO.getIconUrl());
            }
            if(!categoryVO.getPicUrl().startsWith("http")) {
                categoryVO.setPicUrl(imageBaseURL + categoryVO.getPicUrl());
            }
            // 获取对应一级类目下的二级类目
            List<CategoryL2VO> categoryL2VOS = categoryMapper.selectL2ByPID(categoryVO.getId());
            for (CategoryL2VO categoryL2VO : categoryL2VOS) {
                if(!categoryL2VO.getIconUrl().startsWith("http")) {
                    categoryL2VO.setIconUrl(imageBaseURL + categoryL2VO.getIconUrl());
                }
                if(!categoryL2VO.getPicUrl().startsWith("http")) {
                    categoryL2VO.setPicUrl(imageBaseURL + categoryL2VO.getPicUrl());
                }
            }

            categoryVO.setChildren(categoryL2VOS);
        }

        return categoryVOList;
    }

    @Override
    public Category categoryCreate(CategoryBO categoryBO) {

        // 处理图片路径
        if(!StringUtils.isEmpty(categoryBO.getIconUrl())) {
            categoryBO.setIconUrl(categoryBO.getIconUrl().replace(imageBaseURL, ""));
        }
        if(!StringUtils.isEmpty(categoryBO.getPicUrl())) {
            categoryBO.setPicUrl(categoryBO.getPicUrl().replace(imageBaseURL, ""));
        }

        int result = categoryMapper.insertSelective(categoryBO);

        if(result == 0) {
            return null;
        }

        Category category = categoryMapper.selectByPrimaryKey(categoryBO.getId());
        if(!category.getIconUrl().startsWith("http")) {
            category.setIconUrl(imageBaseURL + category.getIconUrl());
        }
        if(!category.getPicUrl().startsWith("http")) {
            category.setPicUrl(imageBaseURL + category.getPicUrl());
        }

        return category;
    }

    @Override
    public int categoryUpdate(CategoryBO categoryBO) {

        // 处理图片路径
        if(!StringUtils.isEmpty(categoryBO.getIconUrl())) {
            categoryBO.setIconUrl(categoryBO.getIconUrl().replace(imageBaseURL, ""));
        }
        if(!StringUtils.isEmpty(categoryBO.getPicUrl())) {
            categoryBO.setPicUrl(categoryBO.getPicUrl().replace(imageBaseURL, ""));
        }

        // 更改当前类目
        int result = categoryMapper.updateCategoryByID(categoryBO);
        if(result == 0) {
            return result;
        }

        // 如果当前类目有子类目，将所有子类目更改到当前类目更改后的类目下
        // 即更改子类目的pid
        List<CategoryL2BO> children = categoryBO.getChildren();
        if(children != null && children.size() != 0) {
            for (CategoryL2BO child : children) {
                // 处理图片路径
                if(!StringUtils.isEmpty(child.getIconUrl())) {
                    child.setIconUrl(child.getIconUrl().replace(imageBaseURL, ""));
                }
                if(!StringUtils.isEmpty(child.getPicUrl())) {
                    child.setPicUrl(child.getPicUrl().replace(imageBaseURL, ""));
                }

                result = categoryMapper.updatePidByID(categoryBO.getPid(), child.getId());
                if(result == 0) {
                    return result;
                }
            }
        }


        return result;
    }

    @Override
    public int categoryDelete(CategoryBO categoryBO) {

        int result = categoryMapper.changeDeletedByID(categoryBO.getId());
        if(result == 0) {
            return result;
        }

        // 遍历子类目，将所有子类目进行逻辑删除
        List<CategoryL2BO> children = categoryBO.getChildren();
        if(children != null && children.size() != 0) {
            for (CategoryL2BO child : children) {
                result = categoryMapper.changeDeletedByID(child.getId());
                if(result == 0) {
                    return result;
                }
            }
        }

        return result;
    }

    @Override
    public OrderListVO getOrderList(OrderListBO orderListBO) {
        PageHelper.startPage(orderListBO.getPage(), orderListBO.getLimit());
        //根据用户提交的条件从数据库取出全部符合条件的数据
        List<Order> orderList = orderMapper.selectOrderByPost(orderListBO);

        PageInfo<Order> brandVOPageInfo = new PageInfo<>(orderList);
        int totalCount = (int) brandVOPageInfo.getTotal();

        OrderListVO orderListVO = new OrderListVO();
        //orderListVO.setTotal(orderList.size());
        orderListVO.setTotal(totalCount);
        orderListVO.setItems(orderList);
        return orderListVO;
    }

    @Override
    public OrderDetailVO getOrderDetailById(Integer id) {
        /**
         * OrderDetailVO对象三个属性，须分别查询order_goods、user、order表
         */
        //根据用户提交的订单id查询订单中的商品
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByOrderId(id);
        //根据id查询订单信息
        Order order = orderMapper.selectByPrimaryKey(id);
        //从order中获取userId，根据userId查询用户信息
        Integer userId = order.getUserId();
        User user = userMapper.selectByPrimaryKey(userId);

        OrderDetailVO orderDetailVO = new OrderDetailVO();
        orderDetailVO.setOrderGoods(orderGoods);
        orderDetailVO.setOrder(order);
        orderDetailVO.setUser(user);
        return orderDetailVO;
    }

    @Override
    public int orderRefund(OrderRefundBO orderRefundBO) {
        /**
         * 修改订单order_status为已退款203
         */
        Order order = new Order();
        order.setId(orderRefundBO.getOrderId());
        order.setOrderStatus((short) 203);
        Date date = new Date();
        order.setUpdateTime(date);
        int affectRows = orderMapper.updateByPrimaryKeySelective(order);
        if (affectRows != 1) {
            return 500;
        }
        return 0;
    }

    @Override
    public int orderShip(OrderShipBO orderShipBO) {
        /**
         * 修改订单order_status为已发货301、发货公司和发货编号为提交的值
         */
        Order order = new Order();
        order.setId(orderShipBO.getOrderId());
        order.setOrderStatus((short) 301);
        order.setShipChannel(orderShipBO.getShipChannel());
        order.setShipSn(orderShipBO.getShipSn());
        Date date = new Date();
        order.setShipTime(date);
        order.setUpdateTime(date);
        int affectRows = orderMapper.updateByPrimaryKeySelective(order);
        if (affectRows != 1) {
            return 500;
        }
        return 0;
    }

    @Override
    public IssueListVO getIssueList(IssueListBO issueListBO) {
        PageHelper.startPage(issueListBO.getPage(), issueListBO.getLimit());
        //根据用户提交的条件从数据库取出全部符合条件的数据
        List<Issue> issueList = issueMapper.selectByQuestion(issueListBO);
        PageInfo<Issue> brandVOPageInfo = new PageInfo<>(issueList);
        long total = brandVOPageInfo.getTotal();
        IssueListVO issueListVO = new IssueListVO();
        issueListVO.setTotal(total);
        issueListVO.setItems(issueList);
        return issueListVO;
    }

    @Override
    public Issue issueCreate(IssuecreateBO issuecreateBO) {
        Issue issue = new Issue();
        issue.setAnswer(issuecreateBO.getQuestion());
        issue.setQuestion(issuecreateBO.getQuestion());
        Date date = new Date();
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        issue.setAddTime(date);
        issue.setUpdateTime(date);
        int affectRows = issueMapper.insertSelective(issue);
        if (affectRows != 1) {
            return null;
        }
        return issue;
    }

    @Override
    public Issue issueUpdate(Issue issue) {
        Date date = new Date();
        issue.setUpdateTime(date);
        int affectRows = issueMapper.updateByPrimaryKey(issue);
        if (affectRows != 1) {
            return null;
        }
        return issue;
    }

    @Override
    public int issueDelete(Issue issue) {
        issue.setDeleted(true);
        int affectRows = issueMapper.updateByPrimaryKeySelective(issue);
        if (affectRows != 1) {
            return 500;
        }
        return 0;
    }

    @Override
    public KeywordListVO getKeywordList(KeywordListBO keywordListBO) {
        PageHelper.startPage(keywordListBO.getPage(), keywordListBO.getLimit());
        List<Keyword> keywordList = keywordMapper.selectByPost(keywordListBO);
        PageInfo<Keyword> brandVOPageInfo = new PageInfo<>(keywordList);
        long total = brandVOPageInfo.getTotal();
        KeywordListVO keywordListVO = new KeywordListVO();
        keywordListVO.setTotal((int) total);
        keywordListVO.setItems(keywordList);
        return keywordListVO;

    }

    @Override
    public int keywordCreate(Keyword keyword) {
        Date date = new Date();
        keyword.setAddTime(date);
        keyword.setUpdateTime(date);
        int affectRows = keywordMapper.insertSelective(keyword);
        if (affectRows != 1) {
            return 500;
        }
        return 0;
    }

    @Override
    public int keywordUpdate(Keyword keyword) {
        Date date = new Date();
        keyword.setUpdateTime(date);
        int affectRows = keywordMapper.updateByPrimaryKey(keyword);
        if (affectRows != 1) {
            return 500;
        }
        return 0;
    }

    @Override
    public int keywordDelete(Keyword keyword) {
        keyword.setDeleted(true);
        int affectRows = keywordMapper.updateByPrimaryKey(keyword);
        if (affectRows != 1) {
            return 500;
        }
        return 0;
    }
}





















